package com.jcl.cloud.services.login.service;


import com.jcl.cloud.common.service.exception.JclCrawlException;
import com.jcl.cloud.services.login.constant.LoginTaskRouteEnum;
import com.jcl.cloud.services.login.factory.LoginTaskHandlerFactory;
import com.jcl.cloud.services.login.factory.WebDriverPool;
import com.jcl.cloud.services.login.model.LoginModel;
import com.jcl.cloud.services.login.task.LoginTaskHandler;
import com.jcl.cloud.services.login.task.LoginTaskHandlerWrap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginTaskManagerService {

    @Autowired
    private LoginTaskHandlerFactory loginTaskHandlerFactory;
    @Autowired
    private ThreadPoolService threadPoolService;
    @Autowired
    private RedisService redisService;

    public void createLoginTask(String crawlerId) throws JclCrawlException {

        try {
            //正常情况这里是要对参数进行校验、封装处理
            String siteCode = this.redisService.hget("unicrawler:task:info:"+crawlerId,"siteCode");
            LoginTaskRouteEnum taskRouteEnum = LoginTaskRouteEnum.explain(siteCode);
            LoginTaskHandler loginTaskHandler = this.loginTaskHandlerFactory.getHandler(taskRouteEnum);
            LoginModel loginModel = new LoginModel();
            loginModel.setCrawlerId(crawlerId);
            if(siteCode.equals("qcwy")){
                loginModel.setDriver(WebDriverPool.getInstance().borrowObject("CHROME"));
            }else if(siteCode.equals("zlzp")){
                loginModel.setDriver(WebDriverPool.getInstance().borrowObject("FIREFOX"));
            }
            //新建线程池启动任务
            this.threadPoolService.execute(new LoginTaskHandlerWrap(loginTaskHandler,loginModel));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
